﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Administration;
using System.DirectoryServices;

namespace g2rcp
{
    public partial class G2RCPSettings : OperationsPage
    {
        string TextErrorFieldsMissing = "Some mandatory fields are missing.";
        string TextErrorTestLdapConnection = "Unable to connect to LDAP for following reason:<br/>{0}<br/>It may be expected if w3wp process of central admin has intentionally no access to LDAP server.";
        string TextConnectionSuccessful = "Connection successful.";
        
        //LDAPClaimProviderTrustConfiguration CurrentTrustSettings;
        G2RCPConfig PersistedObject;

        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // Get SPPersisted Object and create it if it doesn't exist
                PersistedObject = G2RCPConfig.GetFromConfigDB;
                if (PersistedObject == null)
                {
                    this.Web.AllowUnsafeUpdates = true;
                    PersistedObject = G2RCPConfig.CreatePersistedObject();
                    this.Web.AllowUnsafeUpdates = false;
                }
            });

            //if (PersistedObject.trustConfig == null || !PersistedObject.trustConfig.TryGetValue(CurrentTrustedLoginProvider.Id, out CurrentTrustSettings))
            //{
            //    CurrentTrustSettings = new LDAPClaimProviderTrustConfiguration { UseSharePointDomain = true };
            //    AddOrUpdateTrustInPersistedObject();
            //}

            if (!this.IsPostBack)
            {
                PopulateFields();
            }
            
        }

        private void PopulateFields()
        {
            this.ChkGroupsToRoles.Checked = PersistedObject.GroupsToRoles;
            this.Txtcpt.Text = PersistedObject.cpt;
            this.Txtcpn.Text = PersistedObject.cpn;
            if (PersistedObject.UseSharePointDomain)
                this.RbUseServerDomain.Checked = true;
            else
                this.RbUseCustomConnection.Checked = true;
            this.TxtLdapConnectionString.Text = PersistedObject.LDAPConnectionString;
            this.TxtLdapUsername.Text = PersistedObject.LDAPUserName;
            this.TxtLdapPassword.Text = PersistedObject.LDAPPassword;
            this.TxtLdapFilter.Text = PersistedObject.LDAPfilter;
        }

        protected void UpdateTrustConfiguration()
        {
            if (null == PersistedObject)
            {
                G2RCP.LogToULS(
                    String.Format("PersistedObject {0} should not be null.", G2RCPConfig.G2RCPPersistecObjectName),
                    TraceSeverity.Unexpected,
                    EventSeverity.Error);
                return;
            }

            PersistedObject.GroupsToRoles = this.ChkGroupsToRoles.Checked;
            PersistedObject.cpt = this.Txtcpt.Text;
            PersistedObject.cpn = this.Txtcpn.Text;
            PersistedObject.UseSharePointDomain = this.RbUseServerDomain.Checked;
            PersistedObject.LDAPConnectionString = this.TxtLdapConnectionString.Text;
            PersistedObject.LDAPUserName = this.TxtLdapUsername.Text;
            PersistedObject.LDAPPassword =  this.TxtLdapPassword.Text;
            PersistedObject.LDAPfilter =  this.TxtLdapFilter.Text;
        
            // Update object in database
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                this.Web.AllowUnsafeUpdates = true;
                PersistedObject.Update();
                this.Web.AllowUnsafeUpdates = false;

                G2RCP.LogToULS(
                    String.Format("Updated G2RCP configuration through PersistedObject {0}.", G2RCPConfig.G2RCPPersistecObjectName),
                    TraceSeverity.Medium,
                    EventSeverity.Information);

            });
        }

        protected void ValidateLdapConnection()
        {
            if (this.TxtLdapConnectionString.Text == String.Empty || this.TxtLdapPassword.Text == String.Empty || this.TxtLdapUsername.Text == String.Empty)
            {
                this.LabelErrorTestLdapConnection.Text = TextErrorFieldsMissing;
                return;
            }

            try
            {
                DirectoryEntry de = new DirectoryEntry(this.TxtLdapConnectionString.Text, this.TxtLdapUsername.Text, this.TxtLdapPassword.Text);
                DirectorySearcher deSearch = new DirectorySearcher();
                deSearch.SearchRoot = de;
                deSearch.FindOne();
                this.LabelTestLdapConnectionOK.Text = TextConnectionSuccessful;
            }
            catch (Exception ex)
            {
                this.LabelErrorTestLdapConnection.Text = String.Format(TextErrorTestLdapConnection, ex.Message);
            }
        }

        protected void BtnOK_Click(Object sender, EventArgs e)
        {
            if (this.RbUseCustomConnection.Checked && (this.TxtLdapConnectionString.Text == String.Empty || this.TxtLdapUsername.Text == String.Empty || this.TxtLdapPassword.Text == String.Empty))
            {
                this.LabelErrorMessage.Text = TextErrorFieldsMissing;
                return;
            }
            this.UpdateTrustConfiguration();
            RedirectToOperationsPage();
        }

        protected void BtnTestLdapConnection_Click(Object sender, EventArgs e)
        {
            this.ValidateLdapConnection();
        }
        
    }
}
